package com.sqx.modules.health.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sqx.modules.health.common.Constants;
import com.sqx.modules.health.common.Result;
import com.sqx.modules.health.entity.Agent;
import com.sqx.modules.health.entity.Hospital;
import com.sqx.modules.health.entity.NcgDeviceWatch;
import com.sqx.modules.sys.entity.SysUserEntity;
import com.sqx.modules.health.service.IAgentService;
import com.sqx.modules.health.service.IHospitalService;
import com.sqx.modules.health.service.INcgDeviceWatchService;
import com.sqx.modules.health.service.IUserService;
import com.sqx.modules.health.utils.ExcelImportUtil;
import com.sqx.modules.health.utils.MyBeanUtil;
import com.sqx.modules.health.vo.NcgDeviceWatchVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * 血糖仪设备管理
 *
 * @author gxy
 * @since 2022-05-23
 */
@Slf4j
@RestController
@RequestMapping("/health/ncgDeviceECG")
public class NcgDevice_ECGController {
    @Autowired
    private INcgDeviceWatchService ncgDeviceWatchService;

    @Autowired
    private IHospitalService hospitalService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IAgentService agentService;

    // 新增或更新
    @PostMapping("/save")
    @ApiOperation(value = "新增或更新智能手表设备表", notes = "新增或更新智能手表设备表")
    public Result save(@RequestBody NcgDeviceWatch ncgDeviceWatch) {
        if (ObjectUtil.isEmpty(ncgDeviceWatch.getId())) {
            ncgDeviceWatch.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
            ncgDeviceWatch.setCreatetime(LocalDateTime.now());
            ncgDeviceWatch.setIsdelete(0);
            ncgDeviceWatch.setIsenable(0);
            ncgDeviceWatch.setType("4");
        } else {
            ncgDeviceWatch.setUpdatetime(LocalDateTime.now());
        }
        return Result.success(ncgDeviceWatchService.saveOrUpdate(ncgDeviceWatch));
    }


    // 分页查询
    @GetMapping("/findPage")
    @ApiOperation(value = "分页查询智能手表设备表", notes = "分页查询智能手表设备表")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(required = false, defaultValue = "") Long loginHid,
                           @RequestParam(required = false, defaultValue = "") String imei,
                           @RequestParam(required = false, defaultValue = "") Integer hid) {
        QueryWrapper<NcgDeviceWatch> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(imei), "imei", imei);
        if (ObjectUtil.isNotEmpty(loginHid)) {
            queryWrapper.eq("hid", loginHid);
        }
        if (ObjectUtil.isNotEmpty(hid)) {
            queryWrapper.eq("hid", hid);
        }
        queryWrapper.eq("type", 4);
        queryWrapper.orderByDesc("id");
        Page<NcgDeviceWatch> page = ncgDeviceWatchService.page(new Page<>(pageNum, pageSize), queryWrapper);
        List<NcgDeviceWatchVO> ncgDeviceWatchVOS = MyBeanUtil.collectionCopy(page.getRecords(), NcgDeviceWatchVO.class);
        Page<NcgDeviceWatchVO> result = new Page<>();
        result.setRecords(ncgDeviceWatchVOS);
        result.setTotal(page.getTotal());
        for (NcgDeviceWatchVO record : result.getRecords()) {
            if (ObjectUtil.isNotEmpty(record.getHid())) {
                Hospital hospital = hospitalService.getById(record.getHid());
                record.setHName(ObjectUtil.isEmpty(hospital.getName()) ? hospital.getAbbreviation() : hospital.getName());
            }

            if (ObjectUtil.isNotEmpty(record.getUid())) {
                SysUserEntity user = userService.getRedisByUid(record.getUid());
                if (ObjectUtil.isEmpty(user)) {
                    record.setUName("无患者信息");
                } else {
                    record.setUName(ObjectUtil.isEmpty(user.getNickName()) ? user.getUsername() : user.getNickName());
                }
            }

            if (ObjectUtil.isNotEmpty(record.getAgentid())) {
                Agent agent = agentService.getById(record.getAgentid());
                record.setAgentName(ObjectUtil.isEmpty(agent.getName()) ? agent.getAbbreviation() : agent.getName());
            }

            if (ObjectUtil.isNotEmpty(record.getDoctorid())) {
                SysUserEntity user = userService.getRedisByUid(record.getDoctorid());
                if (ObjectUtil.isEmpty(user)) {
                    record.setDoctorName("无医生信息");
                } else {
                    record.setDoctorName(user.getNickName());
                }
            }

        }
        return Result.success(result);
    }


    @Transactional
    @PostMapping("/insertBath")
    public Result insertBath(MultipartFile file) {
        NcgDeviceWatchVO vo = new NcgDeviceWatchVO();

        NcgDeviceWatch ncgDeviceWatch = new NcgDeviceWatch();

        List<List<String>> lists = ExcelImportUtil.importExcel(file);
        if (lists.size() == 0) {
            return Result.error(Constants.CODE_500, "导入失败,请检查文件!!!");
        }
        int succ = 0;
        List<Integer> errLine = new ArrayList<>();

        try {
            for (int i = 0; i < lists.size(); i++) {
                vo.setImei(lists.get(i).get(0));
                if (getHospitalId(lists.get(i).get(1)) == null) {
                    errLine.add(i + 1);
                    continue;
                } else {
                    vo.setHid(getHospitalId(lists.get(i).get(1)));
                }
                switch (lists.get(i).get(2)) {
                    case "平台库存":
                        vo.setStatus(0);
                        break;
                    case "医院库存":
                        vo.setStatus(1);
                        break;
                    case "用户解绑":
                        vo.setStatus(2);
                        break;
                    case "用户绑定":
                        vo.setStatus(3);
                        break;
                    case "医护领用":
                        vo.setStatus(4);
                        break;
                    case "报修":
                        vo.setStatus(5);
                        break;
                    case "平台报修":
                        vo.setStatus(6);
                        break;
                    case "平台报废":
                        vo.setStatus(7);
                        break;
                    default:
                        vo.setStatus(0);
                        break;
                }

                vo.setUuid(UUID.randomUUID().toString().replaceAll("-", ""));
                vo.setCreatetime(LocalDateTime.now());
                vo.setIsdelete(0);
                vo.setIsenable(1);
                vo.setId(null);
                vo.setType("4");
                BeanUtil.copyProperties(vo, ncgDeviceWatch);
                ncgDeviceWatchService.save(ncgDeviceWatch);
                succ += 1;
            }
            return Result.success("成功导入" + succ + "条,失败" + errLine.size() + "条,在" + errLine + "行");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error(Constants.CODE_500, "导入失败!!!");
        }
    }

    private Long getHospitalId(String hospitalName) {
        return hospitalService.getHospitalId(hospitalName);
    }

}
